<template>
  <div class="cartoon-collection">
    <el-tabs v-model="data.activeName" lazy>
      <el-tab-pane label="采集漫画信息" name="first">
        <div class="link-collection coll">
          <div class="mall-main">
            <div class="link-key">
              <div class="form-item">
                <p>商品链接<span class="themeColor">(一行一个,获取漫画详情或章节信息和内容)</span></p>
              </div>
              <div class="form-item right-none">
                <el-input type="textarea" v-model="data.linkKey" rows="7" resize="none"></el-input>
              </div>
              <div class="form-item">
                <span>范例：</span>
                <p style="color: red">漫客栈：https://www.mkzhan.com/216151/</p>
              </div>
            </div>
            <div class="main-btn">
              <div class="form-item">
                <el-button v-if="flag" type="primary" @click="linkSearch">开始采集</el-button>
                <el-button v-else type="primary" plain @click="flag = true">取消采集</el-button>
                <el-button v-if="radio1 == '1'" type="primary" @click="exportSearch(1)">导出漫画信息</el-button>
                <el-button v-else type="primary" @click="exportSearch(2)">导出章节信息</el-button>
                <!-- <el-button v-if="radio1 == '2'" type="primary" @click="exportChapterAll">导出所有章节内容</el-button> -->
                <!-- <el-button type="primary" @click="exportChapter">导出章节内容</el-button> -->
                <el-button type="danger" @click="removeAll">清理列表</el-button>
              </div>
              <!-- <div class="form-item">
                <el-button type="danger"  @click="removeAll">清理列表</el-button>
                <el-button type="primary" @click="exportChapter">导出章节内容</el-button>
              </div> -->
              <div class="form-item">
                <el-radio-group v-model="radio1">
                  <el-radio label="1" size="large">漫画详情</el-radio>
                  <el-radio label="2" size="large">漫画章节</el-radio>
                </el-radio-group>
              </div>
              <!-- <div class="form-item" v-show="radio1 == '2'">
                <el-checkbox v-model="checked">获取章节内容</el-checkbox>
                <el-tooltip placement="top">
                  <template #content>如果勾选该选项，可能会导致采集时间延长，请耐心等待... </template>
                  <el-icon size="30">
                    <InfoFilled />
                  </el-icon>
                </el-tooltip>
              </div> -->
              <!-- <div class="form-item" v-show="radio1 == '1'">
            <el-checkbox v-model="checked1">获取章节列表</el-checkbox>
            <el-tooltip placement="top">
              <template #content>如果勾选该选项，可能会导致采集时间延长，请耐心等待... </template>
              <el-icon size="30">
                <InfoFilled />
              </el-icon>
            </el-tooltip>
          </div> -->
            </div>
            <div class="carry-log">
              <div class="form-item">
                <p>执行日志</p>
              </div>
              <div class="form-item">
                <el-input type="textarea" v-model="linkLog" rows="7" disabled resize="none"></el-input>
              </div>
            </div>
          </div>
        </div>
        <div class="table-box coll">
          <el-table
            v-if="radio1 == '1'"
            ref="workbenchTable"
            :height="data.tableHeight"
            :data="data.tableData1"
            tooltip-effect="dark"
            empty-text="暂无数据"
            style="width: 100%"
            :header-cell-style="{
              textAlign: 'center',
              backgroundColor: '#f5f7fa'
            }"
            :cell-style="{ textAlign: 'center' }"
            :row-style="{ height: '80px' }"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="60" fixed />
            <el-table-column label="序号" width="60">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="漫画名称" min-width="120px" prop="title" />
            <!-- <el-table-column label="漫画简介" width="80px" align="center">
          <template #default="scope">
            <img v-if="scope.row.img_url" :src="scope.row.img_url" alt="" class="cover_img" />
            <img v-else src="~@/assets/images/default.jpg" alt="" class="cover_img" />
          </template>
        </el-table-column> -->
            <el-table-column label="漫画简介" show-overflow-tooltip min-width="160px" prop="content" />
            <el-table-column label="作者" min-width="120px" prop="author_id" />
            <el-table-column label="价格" min-width="120px" prop="price" />
            <el-table-column label="是否vip" min-width="120px" prop="is_vip">
              <template #default="scope">
                <span>{{ scope.row.is_vip == 0 ? '免费' : '会员' }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column label="操作" min-width="140px">
          <template #default="{ row }">
            <el-button v-if="row.page" size="small" type="primary" @click="exportChapter(row.page, row.title)"
              >导出章节内容</el-button
            >
            <el-button size="small" type="danger">删除</el-button>
          </template>
        </el-table-column> -->
          </el-table>
          <el-table
            v-else
            ref="workbenchTable"
            :height="data.tableHeight"
            :data="data.tableData.slice((data.page - 1) * data.pageSize, data.page * data.pageSize)"
            tooltip-effect="dark"
            empty-text="暂无数据"
            style="width: 100%"
            :header-cell-style="{
              textAlign: 'center',
              backgroundColor: '#f5f7fa'
            }"
            :cell-style="{ textAlign: 'center' }"
            :row-style="{ height: '80px' }"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="60" fixed />
            <el-table-column label="序号" width="60">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="章节名称" min-width="120px" prop="title" />
            <el-table-column label="封面" width="80px" align="center">
              <template #default="scope">
                <img v-if="scope.row.img_url" :src="scope.row.img_url" alt="" class="cover_img" />
                <img v-else src="~@/assets/images/default.jpg" alt="" class="cover_img" />
              </template>
            </el-table-column>
            <el-table-column label="章节别名" min-width="120px" prop="title_alias" />
            <el-table-column label="价格" min-width="120px" prop="price" />
            <el-table-column label="是否vip" min-width="120px" prop="is_vip">
              <template #default="scope">
                <span>{{ scope.row.is_vip == 0 ? '免费' : '会员' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="140px">
              <template #default="{ row }">
                <el-button v-if="row.page" size="small" type="primary" @click="exportChapter(row.page, row.title)"
                  >导出章节内容</el-button
                >
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination" v-if="radio1 == '2'">
            <el-pagination
              v-model:currentPage="data.page"
              v-model:page-size="data.pageSize"
              :page-sizes="[100, 200, 300]"
              background
              layout="sizes,prev, pager, next"
              :total="data.tableData.length"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            >
              <span style="margin-right: 5px">当前共{{ data.tableData.length }}条</span>
            </el-pagination>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="采集漫画/小说链接" name="second">
        <div class="link-wrap coll">
          <div class="mall-main">
            <div class="main-btn">
              <div class="form-item">
                <el-button v-if="flag" type="primary" @click="getCartoonLink">开始采集</el-button>
                <el-button v-else type="primary" plain>取消采集</el-button>
                <el-button type="primary" @click="exportLink">导出链接</el-button>
                <el-button v-if="radio2 == '2'" type="warning" @click="setCollection">一键收藏</el-button>
                <el-button v-if="radio2 === '3'" type="warning" @click="collectionVideo">一键收藏</el-button>
                <!-- <el-button v-if="radio2 == '2'" type="warning" @click="setCollection">取消收藏</el-button> -->
              </div>
              <div class="form-item">
                <el-radio-group v-model="radio2">
                  <el-radio label="1" size="large">漫画链接</el-radio>
                  <el-radio label="2" size="large">小说链接</el-radio>
                  <el-radio label="3" size="large">视频链接</el-radio>
                </el-radio-group>
              </div>
              <div class="form-item">
                <span class="label">开始页码：</span>
                <el-input v-model="data.startPage" style="width: 80px" size="default" clearable />
                <span class="label">总页码：</span>
                <el-input v-model="data.endPage" style="width: 80px" size="default" clearable />
              </div>
              <div class="form-item" v-if="radio2 == '2'">
                <span class="label">小说分类：</span>
                <el-select v-model="data.category_id" class="text-input">
                  <el-option v-for="(item, index) in categoryList" :key="index" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </div>
            <div class="carry-log">
              <div class="form-item">
                <p>执行日志</p>
              </div>
              <div class="form-item">
                <el-input type="textarea" v-model="linkLog" rows="7" disabled resize="none"></el-input>
              </div>
            </div>
          </div>
        </div>
        <div class="table-box coll">
          <el-table
            id="table"
            ref="workbenchTable"
            :height="data.tableHeight"
            :data="data.tableData3.slice((data.page - 1) * data.pageSize, data.page * data.pageSize)"
            tooltip-effect="dark"
            empty-text="暂无数据"
            style="width: 100%"
            :header-cell-style="{
              textAlign: 'center',
              backgroundColor: '#f5f7fa'
            }"
            :cell-style="{ textAlign: 'center' }"
            :row-style="{ height: '80px' }"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="60" fixed />
            <el-table-column label="序号" width="60">
              <template #default="scope">
                {{ scope.$index + 1 + (data.page - 1) * data.pageSize }}
              </template>
            </el-table-column>
            <el-table-column label="漫画/小说链接" prop="url">
              <template #default="scope">
                {{ scope.row.url }} <el-icon @click="copyText(scope.row.url)"><DocumentCopy /></el-icon>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              v-model:currentPage="data.page"
              v-model:page-size="data.pageSize"
              :page-sizes="[20, 100, 200, 300]"
              background
              layout="sizes,prev, pager, next"
              :total="data.tableData3.length"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            >
              <span style="margin-right: 5px">当前共{{ data.tableData3.length }}条</span>
            </el-pagination>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="采集小说信息" name="third">
        <div class="link-collection coll">
          <div class="mall-main">
            <div class="link-key">
              <div class="form-item">
                <p>商品链接<span class="themeColor">(一行一个,获取小说详情或小说信息)</span></p>
              </div>
              <div class="form-item right-none">
                <el-input type="textarea" v-model="data.linkKey" rows="7" resize="none"></el-input>
              </div>
              <div class="form-item">
                <span>范例：</span>
                <p style="color: red">七猫小说网:https://www.9biquge.com/42/42857/</p>
              </div>
            </div>
            <div class="main-btn">
              <div class="form-item">
                <el-button v-if="flag" type="primary" @click="linkNovelSearch">开始采集</el-button>
                <el-button v-else type="primary" plain @click="flag = true">取消采集</el-button>
                <el-button v-if="radio1 == '1'" type="primary" @click="exportSearch(3)">导出小说信息</el-button>
                <el-button v-else type="primary" @click="exportSearch(4)">导出章节信息</el-button>
                <el-button type="danger" @click="removeAll">清理列表</el-button>
              </div>
              <div class="form-item">
                <el-button type="danger" @click="setCollection(1)">一键收藏</el-button>
              </div>
              <div class="form-item">
                <el-radio-group v-model="radio1">
                  <el-radio label="1" size="large">小说详情</el-radio>
                  <el-radio label="2" size="large">小说章节</el-radio>
                </el-radio-group>
              </div>
            </div>
            <div class="carry-log">
              <div class="form-item">
                <p>执行日志</p>
              </div>
              <div class="form-item">
                <el-input type="textarea" v-model="linkLog" rows="7" disabled resize="none"></el-input>
              </div>
            </div>
          </div>
        </div>
        <div class="table-box coll">
          <el-table
            v-if="radio1 == '1'"
            ref="workbenchTable"
            :height="data.tableHeight"
            :data="data.novelData"
            tooltip-effect="dark"
            empty-text="暂无数据"
            style="width: 100%"
            :header-cell-style="{
              textAlign: 'center',
              backgroundColor: '#f5f7fa'
            }"
            :cell-style="{ textAlign: 'center' }"
            :row-style="{ height: '80px' }"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="60" fixed />
            <el-table-column label="序号" width="60">
              <template #default="scope">
                {{ scope.$index + 1 + (data.page - 1) * data.pageSize }}
              </template>
            </el-table-column>
            <el-table-column label="小说名称" min-width="120px" prop="name" />
            <el-table-column label="封面" width="80px" align="center">
              <template #default="scope">
                <img v-if="scope.row.cover_lateral" :src="scope.row.cover_lateral" alt="" class="cover_img" />
                <img v-else src="~@/assets/images/default.jpg" alt="" class="cover_img" />
              </template>
            </el-table-column>
            <el-table-column label="简介" show-overflow-tooltip min-width="160px" prop="intro" />
            <el-table-column label="作者" min-width="120px" prop="author" />
          </el-table>
          <el-table
            v-else
            ref="workbenchTable"
            :height="data.tableHeight"
            :data="data.novelChapterData.slice((data.page - 1) * data.pageSize, data.page * data.pageSize)"
            tooltip-effect="dark"
            empty-text="暂无数据"
            style="width: 100%"
            :header-cell-style="{
              textAlign: 'center',
              backgroundColor: '#f5f7fa'
            }"
            :cell-style="{ textAlign: 'center' }"
            :row-style="{ height: '80px' }"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="60" fixed />
            <el-table-column label="序号" width="60">
              <template #default="scope">
                {{ scope.$index + 1 + (data.page - 1) * data.pageSize }}
              </template>
            </el-table-column>
            <el-table-column label="章节名称" min-width="120px" prop="title" />
            <el-table-column label="章节别名" min-width="120px" prop="title_alias" />
            <!-- <el-table-column label="操作" min-width="140px">
              <template #default="{ row }">
                <el-button v-if="row.page" size="small" type="primary" @click="exportChapter(row.page, row.title)"
                  >导出章节内容</el-button
                >
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-table-column> -->
          </el-table>
          <div class="pagination" v-if="radio1 == '2'">
            <el-pagination
              v-model:currentPage="data.page"
              v-model:page-size="data.pageSize"
              :page-sizes="[100, 200, 300]"
              background
              layout="sizes,prev, pager, next"
              :total="data.novelChapterData.length"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            >
              <span style="margin-right: 5px">当前共{{ data.novelChapterData.length }}条</span>
            </el-pagination>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, getCurrentInstance, onMounted, watch, ref } from 'vue'
  import {
    delay,
    handleKey,
    getTableHeight,
    reduceData,
    exportXls,
    exportExcelDataCommon,
    copyText
  } from '@/hooks/utils'
  import { DocumentCopy } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import { categoryList } from '../data/index'

  let flag = ref<Boolean>(true)
  let checked = ref<Boolean>(false)
  let checked1 = ref<Boolean>(false)
  let linkLog = ref<String>('')
  const radio1 = ref('1')
  const radio2 = ref('1')

  // @ts-ignore
  const { proxy } = getCurrentInstance()
  const api = proxy.$api
  const data = reactive({
    linkKey: '',
    tableData: [], //漫画章节列表
    tableHeight: 0,
    chapterSelection: [],
    tableData1: [], //漫画列表
    activeName: 'first',
    startPage: '1',
    endPage: '5',
    tableData3: [], //小说/漫画链接
    novelData: [], //小说列表
    novelChapterData: [], //小说章节列表
    page: 1,
    pageSize: 20,
    total: 0,
    category_id: 'xuanhuan'
  })
  onMounted(() => {
    data.tableHeight = getTableHeight(500)
    console.log(data.tableHeight, 'data.tableHeight')
  })
  // 链接采集漫画信息
  async function linkSearch() {
    linkLog.value = ''
    if (!data.linkKey) {
      return (linkLog.value = ',漫画链接不能为空！')
    }
    linkLog.value = '采集中...\n' + linkLog.value
    flag.value = false
    const linkArr = Array.from(new Set(handleKey(data.linkKey)))
    const linkArrLength = linkArr.length
    for (let i = 0; i < linkArrLength; i++) {
      let item = linkArr[i]
      let comicId = ''
      let chapterId = ''
      let execPlatform = /(mkzhan.com)/g
      let platform = item.match(execPlatform)
      let platformId = 1
      if (!platform) {
        linkLog.value = `${i + 1}/${linkArrLength}暂不支持此平台连接，请检查链接是否正确！\n` + linkLog.value
      }
      if (flag.value == true) {
        linkLog.value = `正在取消采集中，请稍等....\n` + linkLog.value
        break
      }
      try {
        switch (platform && platform[0]) {
          case 'mkzhan.com': //漫客栈
            comicId = (item as any).match(/com\/(.+)\//)[1]
            // comicId = ids[0]
            // chapterId = ids[1]
            platformId = 1
            break
        }
      } catch (error) {
        console.log(error)
        linkLog.value = `${i + 1}/${linkArrLength}未从链接中获取到漫画id，请检查链接是否正确！\n` + linkLog.value
        continue
      }

      if (comicId.length < 2) {
        linkLog.value = `${i + 1}/${linkArrLength}未从链接中获取到漫画id，请检查链接是否正确！\n` + linkLog.value
        continue
      }
      if (radio1.value == '1') {
        try {
          const param = {
            comicId,
            chapterId,
            method: 'GET',
            platform: platformId,
            detail: 1
          }
          const res = await api.queryDetailById(param)
          console.log(res, 'res', param)
          if (res.code != 200) {
            linkLog.value =
              `${i + 1}/${linkArrLength},漫画${comicId}采集失败,【${res.code}】${res.msg || ''}\n` + linkLog.value
          } else {
            if (checked1.value) {
              for (let i = 0; i < res.data.length; i++) {
                const element = res.data[i]
                param['chapterId'] = element.chapter_id
                element['url'] = item
                if (element.is_vip == '1') {
                  linkLog.value =
                    `${i + 1}/${res.data.length},章节列表${element.chapter_id}为付费章节，无法采集\n` + linkLog.value
                } else {
                  const res1 = await api.queryDetailById(param)
                  console.log(res1, '===>')
                  if (res1.code == 200) {
                    element['page'] = res1?.data?.page
                    element['url'] = item
                    linkLog.value = `${i + 1}/${res.data.length},章节${element.chapter_id}采集成功\n` + linkLog.value
                  }
                }
              }
            }
            res.data.url = item
            res.data.cover = `${res.data.cover}!cover-400`
            res.data.cover_lateral = `${res.data.cover_lateral}!cover-400`
            console.log(res.data.cover, '======>>>')
            data.tableData1.push(res.data as never)
            console.log(data.tableData1, 'data.tableData1')
            data.tableData1 = reduceData(data.tableData1, 'comic_id')
            linkLog.value = `${i + 1}/${linkArrLength}漫画${comicId}采集成功\n` + linkLog.value
          }
        } catch (error) {
          linkLog.value = `${i + 1}/${linkArrLength}采集失败\n` + linkLog.value
        }
      } else {
        try {
          const param = {
            comicId,
            chapterId,
            method: 'GET',
            platform: platformId,
            detail: 2
          }
          const res = await api.queryDetailById(param)
          console.log(res, 'res', param)
          if (res.code != '200') {
            linkLog.value =
              `${i + 1}/${linkArrLength},漫画${comicId}采集失败,【${res.code}】${res.msg || ''}\n` + linkLog.value
          } else {
            if (checked.value) {
              for (let i = 0; i < res.data.length; i++) {
                if (flag.value == true) {
                  linkLog.value = `正在取消采集中，请稍等....\n` + linkLog.value
                  break
                }
                const element = res.data[i]
                element['url'] = item
                param['chapterId'] = element.chapter_id
                if (element.is_vip == '1') {
                  linkLog.value =
                    `${i + 1}/${res.data.length},章节${element.chapter_id}为付费章节，无法采集\n` + linkLog.value
                } else {
                  const res1 = await api.queryDetailById(param)
                  console.log(res1, '===>')
                  if (res1.code == 200) {
                    element['page'] = res1?.data?.page
                    linkLog.value = `${i + 1}/${res.data.length},章节${element.chapter_id}采集成功\n` + linkLog.value
                  }
                }
              }
            }
            for (let i = 0; i < res.data.length; i++) {
              const element = res.data[i]
              element['cover'] = `${element['cover']}!cover-400`
              element['platform_chapter'] = element.chapter_id
              element['comicId'] = comicId
              data.tableData.push(element as never)
            }
            // data.tableData = res.data
            // data.tableData = data.tableData.concat(res.data)
            linkLog.value = `${i + 1}/${linkArrLength}漫画${comicId}采集成功\n` + linkLog.value
          }
        } catch (error) {
          linkLog.value = `${i + 1}/${linkArrLength}采集失败\n` + linkLog.value
        }
      }
    }
    data.tableData = reduceData(data.tableData, 'chapter_id')
    flag.value = true
    linkLog.value = '采集完成\n' + linkLog.value
  }
  // 采集漫画链接
  async function getCartoonLink() {
    linkLog.value = ''
    linkLog.value = '采集中...\n' + linkLog.value
    flag.value = false
    if (!data.endPage) {
      data.endPage = '1'
    } else {
      data.endPage = Number(data.endPage) > 50 ? '50' : data.endPage
    }
    if (!data.startPage) {
      data.startPage = '1'
    } else if (Number(data.startPage) > Number(data.endPage)) {
      data.startPage = data.endPage
    }
    let num = parseInt(data.startPage)
    let page = parseInt(data.endPage) + 1
    if (radio2.value == '1') {
      data.tableData3 = []
      console.log(num, page)
      for (let i = num; i < page; i++) {
        const param = {
          platform: 1,
          page: i
        }
        try {
          const res = await api.getCartoonLink(param)
          console.log(res, 'res')
          if (res.code == 200) {
            res.data.forEach((item: any) => data.tableData3.push(item as never))
            linkLog.value = `正在采集第${i}页漫画,共采集到${res.data.length}条数据\n` + linkLog.value
          }
        } catch (error) {
          linkLog.value = `第${i}页采集失败\n` + linkLog.value
        }
      }
    } else if (radio2.value == '2') {
      data.tableData3 = []
      linkLog.value = '小说链接采集时间比较长，请耐心等候...\n' + linkLog.value
      for (let i = num; i < page; i++) {
        const param = {
          category_id: data.category_id,
          page: i
        }
        try {
          const res = await api.getNovelLink(param)
          console.log(res, 'res')
          if (res.code == 200) {
            res.data.forEach((item: any) => data.tableData3.push(item as never))
            linkLog.value = `正在采集第${i}页小说数据,共采集到${res.data.length}条数据\n` + linkLog.value
          }
        } catch (error) {
          linkLog.value = `第${i}页采集失败\n` + linkLog.value
        }
      }
    } else {
      data.tableData3 = []
      linkLog.value = '视频链接采集时间比较长，请耐心等候...\n' + linkLog.value
      for (let i = num; i < page; i++) {
        const param = {
          page: i
        }
        try {
          const res = await api.getVideoLink(param)
          console.log(res, 'res')
          if (res.code == 200) {
            res.data.forEach((item: any) => data.tableData3.push(item as never))
            linkLog.value = `正在采集第${i}页视频数据,共采集到${res.data.length}条数据\n` + linkLog.value
          }
        } catch (error) {
          linkLog.value = `第${i}页采集失败\n` + linkLog.value
        }
      }
    }
    linkLog.value = '采集完成\n' + linkLog.value
    flag.value = true
    data.tableData3 = Array.from(reduceData(data.tableData3, 'url'))
    console.log(data.tableData3, 'tableData3')
  }
  // 链接采集小说
  async function linkNovelSearch() {
    linkLog.value = ''
    if (!data.linkKey) {
      return (linkLog.value = ',小说链接不能为空！')
    }
    linkLog.value = '采集中...\n' + linkLog.value
    flag.value = false
    const linkArr = Array.from(new Set(handleKey(data.linkKey)))
    const linkArrLength = linkArr.length
    for (let i = 0; i < linkArrLength; i++) {
      let item = linkArr[i]
      let comicId = ''
      let execPlatform = /(9biquge.com)/g
      let platform = item.match(execPlatform)
      let pageId = 1
      if (!platform) {
        linkLog.value = `${i + 1}/${linkArrLength}暂不支持此平台连接，请检查链接是否正确！\n` + linkLog.value
      }
      if (flag.value == true) {
        linkLog.value = `正在取消采集中，请稍等....\n` + linkLog.value
        break
      }
      try {
        switch (platform && platform[0]) {
          case '9biquge.com': //漫客栈
            let ids = (item as any).match(/com\/(.+)\//)[1].split('/')
            pageId = ids[0]
            comicId = ids[1]
            break
        }
      } catch (error) {
        console.log(error)
        linkLog.value = `${i + 1}/${linkArrLength}未从链接中获取到小说id，请检查链接是否正确！\n` + linkLog.value
        continue
      }
      console.log(comicId, '====>')
      if (comicId.length == 0) {
        linkLog.value = `${i + 1}/${linkArrLength}未从链接中获取到小说id，请检查链接是否正确！\n` + linkLog.value
        continue
      }
      const param = {
        comicId,
        pageId,
        type: 0
      }
      if (radio1.value == '1') {
        try {
          const res = await api.queryNovelDetail(param)
          console.log(res, 'res', param)
          if (res.code != 200) {
            linkLog.value =
              `${i + 1}/${linkArrLength},小说${comicId}采集失败,【${res.code}】IP限制，请稍后重新采集\n` + linkLog.value
          } else {
            res.data.url = item
            data.novelData.push(res.data as never)
            console.log(data.novelData, 'data.novelData')
            data.novelData = reduceData(data.novelData, 'platform_comic')
            linkLog.value = `${i + 1}/${linkArrLength}${res.data.name}采集成功\n` + linkLog.value
          }
        } catch (error) {
          linkLog.value = `${i + 1}/${linkArrLength}采集失败\n` + linkLog.value
        }
      } else {
        try {
          param.type = 1
          const res = await api.queryNovelDetail(param)
          console.log(res, 'res', param)
          if (res.code != 200) {
            linkLog.value =
              `${i + 1}/${linkArrLength},小说${comicId}采集失败,【${res.code}】IP限制，请稍后重新采集\n` + linkLog.value
          } else {
            data.novelChapterData = data.novelChapterData.concat(res.data)
            data.novelChapterData = reduceData(data.novelChapterData, 'platform_chapter')
            console.log(data.novelChapterData, 'data.novelChapterData')
            linkLog.value = `${i + 1}/${linkArrLength}小说${comicId}采集成功\n` + linkLog.value
          }
        } catch (error) {
          linkLog.value = `${i + 1}/${linkArrLength}采集失败\n` + linkLog.value
        }
      }
    }
    // data.novelChapterData = reduceData(data.novelChapterData, 'chapter_id')
    flag.value = true
    linkLog.value = '采集完成\n' + linkLog.value
  }
  // 一键收藏小说
  async function setCollection(type: number = 0) {
    let result = data.chapterSelection.length > 0 ? data.chapterSelection : data.tableData3
    if (type == 1) {
      result = data.chapterSelection.length > 0 ? data.chapterSelection : data.novelData
    }
    linkLog.value = '开始收藏小说...\n' + linkLog.value
    const linklength = result.length
    for (let i = 0; i < result.length; i++) {
      const item = result[i]
      let pageId = ''
      let comicId = ''
      let execPlatform = /(9biquge.com)/g
      let platform = item['url'].match(execPlatform)
      console.log(platform, 'platformId')
      if (!platform) {
        linkLog.value = `${i + 1}/${linklength}未从链接中获取到小说id，请检查链接是否正确！\n` + linkLog.value
      }
      try {
        switch (platform[0]) {
          case '9biquge.com': //漫客栈
            const strId = (item as any)['url'].match(/com\/(.+)\//)[1].split('/')
            pageId = strId[0]
            comicId = strId[1]
            break
        }
      } catch (error) {
        console.log(error)
        linkLog.value = `${i + 1}/${linklength}未从链接中获取到小说id，请检查链接是否正确！\n` + linkLog.value
        continue
      }
      try {
        const param = {
          pageId,
          comicId
        }
        await delay(1000)
        const res = await api.queryNovelDetail(param)
        console.log(res, 'res')
        if (res.code === 200) {
          const novel = res.data
          linkLog.value = `${i + 1}/${linklength}小说${comicId}采集成功\n` + linkLog.value
          linkLog.value = `开始收藏${novel.name}\n` + linkLog.value
          novel['category_id'] = 1
          // await delay(1000)
          const res1 = await api.addNovel(novel)
          if (res1.code == 200) {
            linkLog.value = `${novel.name}收藏成功\n` + linkLog.value
          } else {
            linkLog.value = `${novel.name}收藏失败\n` + linkLog.value
          }
          console.log(res1, '11')
        } else {
          linkLog.value =
            `${i + 1}/${linklength},小说${comicId}采集失败,【${res.code}】${res.msg || ''}\n` + linkLog.value
        }
      } catch (error) {
        linkLog.value = `${i + 1}/${linklength}采集失败\n` + linkLog.value
      }
    }
    linkLog.value = `$采集完成\n` + linkLog.value
  }
  // 一键收藏视频
  async function collectionVideo(type: number = 0) {
    let result = data.chapterSelection.length > 0 ? data.chapterSelection : data.tableData3
    if (type == 1) {
      result = data.chapterSelection.length > 0 ? data.chapterSelection : data.novelData
    }
    linkLog.value = '开始收藏视频...\n' + linkLog.value
    const linklength = result.length
    for (let i = 0; i < result.length; i++) {
      const item = result[i]
      let pageId = ''
      let comicId = ''
      let execPlatform = /(shnakun.com)/g
      let platform = item['url'].match(execPlatform)
      console.log(platform, 'platformId')
      if (!platform) {
        linkLog.value = `${i + 1}/${linklength}未从链接中获取到视频id，请检查链接是否正确！\n` + linkLog.value
      }
      try {
        switch (platform[0]) {
          case 'shnakun.com': //漫客栈
            comicId = (item as any)['url'].match(/voddetail\/(.+)\./)[1]
            console.log(comicId,'comicId');
            break
        }
      } catch (error) {
        console.log(error)
        linkLog.value = `${i + 1}/${linklength}未从链接中获取到视频id，请检查链接是否正确！\n` + linkLog.value
        continue
      }
      try {
        const param = {
          comicId,
          type: 0
        }
        await delay(1000)
        const res = await api.queryVideolDetail(param)
        console.log(res, 'res')
        if (res.code === 200) {
          const novel = res.data
          linkLog.value = `${i + 1}/${linklength}视频${comicId}采集成功\n` + linkLog.value
          linkLog.value = `开始收藏${novel.name}\n` + linkLog.value
          novel['category_id'] = 1
          // await delay(1000)
          const res1 = await api.addVideo(novel)
          if (res1.code == 200) {
            linkLog.value = `${novel.name}收藏成功\n` + linkLog.value
          } else {
            linkLog.value = `${novel.name}收藏失败\n` + linkLog.value
          }
        } else {
          linkLog.value =
            `${i + 1}/${linklength},视频${comicId}采集失败,【${res.code}】${res.msg || ''}\n` + linkLog.value
        }
      } catch (error) {
        linkLog.value = `${i + 1}/${linklength}采集失败\n` + linkLog.value
      }
    }
    linkLog.value = `$采集完成\n` + linkLog.value
  }
  // 选中的数据
  function handleSelectionChange(val: any) {
    data.chapterSelection = val
  }
  const handleSizeChange = (val: number) => {
    // console.log(`${val} items per page`)
    data.pageSize = val
    data.page = 1
  }
  const handleCurrentChange = (val: number) => {
    data.page = val
    // console.log(`current page: ${val}`)
  }
  // 导出章节列表
  function exportSearch(type: number) {
    let result: any[] = []
    let filename = ''
    let head = {}
    switch (type) {
      case 1:
        filename = '漫画列表'
        head = {
          title: '漫画名称',
          cover: '封面',
          content: '漫画简介',
          author_id: '作者',
          price: '价格',
          is_vip: '是否vip',
          url: '采集链接',
          comic_id: '上家漫画ID',
          cover_lateral: '漫画详情封面'
        }
        result = data.chapterSelection.length > 0 ? data.chapterSelection : data.tableData1
        break
      case 2:
        result = data.chapterSelection.length > 0 ? data.chapterSelection : data.tableData
        filename = '章节列表'
        head = {
          title: '章节名称',
          cover: '封面',
          title_alias: '章节别名',
          price: '价格',
          is_vip: '是否vip',
          url: '采集链接',
          platform_chapter: '上家ID',
          comicId: '上家漫画ID'
        }
        break
      case 3:
        filename = '小说列表'
        head = {
          name: '小说名称',
          cover_lateral: '封面',
          intro: '简介',
          author: '作者',
          url: '采集链接',
          platform_comic: '上家漫画ID',
          pageId: '上家页面id'
        }
        result = data.chapterSelection.length > 0 ? data.chapterSelection : data.novelData
        break
      case 4:
        filename = '小说章节列表'
        head = {
          title: '小说名称',
          title_alias: '章节别名',
          platform_chapter: '上家章节ID',
          platform_comic: '上家漫画ID'
        }
        result = data.chapterSelection.length > 0 ? data.chapterSelection : data.novelChapterData
        break
    }
    console.log(result, 'result')

    const list = result.map((item, index) => {
      const obj: any = {}
      for (const k in item) {
        if (head[k]) {
          obj[head[k]] = item[k]
        }
      }
      return obj
    })
    exportXls(filename, list)
  }
  // 清理列表
  function removeAll() {
    data.tableData = []
    data.tableData1 = []
    data.tableData3 = []
  }
  // 导出漫画链接
  function exportLink() {
    exportExcelDataCommon('漫画/小说链接')
  }
  // 导出章节内容
  function exportChapter(row: any, fileName: string) {
    // const filename = '章节内容'
    exportXls(fileName, row)
  }
  // 导出所有章节内容
  function exportChapterAll() {
    const result = data.chapterSelection.length > 0 ? data.chapterSelection : data.tableData
    if (result.length == 0) {
      return ElMessage.warning('请选择要导出的内容')
    }
    let list: string | any[] = []
    for (let i = 0; i < result.length; i++) {
      const item = result[i]
      if ('page' in item) {
        item.page.forEach((v: any) => {
          v['chapter_id'] = item.chapter_id
        })
        list = list.concat(item['page'])
        console.log(list, '===<')
      }
    }
    console.log(list, '===>')

    if (list.length == 0) {
      return ElMessage.warning('请先采集章节内容再导出')
    }
    exportXls('章节内容', list)
  }
</script>

<style scoped lang="less" src="../css/cartoon-collection.less"></style>
